package com.eclipse.e0113_网络编程.多人聊天_服务器负责转发;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;

public class Client {

	private static Scanner scanner = new Scanner(System.in);

	public static void main(String[] args) throws Exception {

		ClientHandler clientHandler = new ClientHandler();
		clientHandler.start();

		System.out.print("请输入你的姓名：");
		String name = scanner.nextLine();
		clientHandler.sendMessage(name);

		String content = "";

		do {
			System.out.print("请输入要发送的消息：");
			content = scanner.nextLine();
			clientHandler.sendMessage(content);
		} while (!content.equals("88"));

		clientHandler.close();

	}

}

//单独负责网络的交互 接收消息
class ClientHandler extends Thread {

	private int port = 8081;

	private BufferedWriter out;

	private BufferedReader in;

	private Socket client;

	public void run() {
		try {
			// 连接到指定的服务端
			Socket client = new Socket("10.70.30.254", port);
			
			// 建立连接后，构建输出对象
			out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
			
			// 建立连接后，构建输入对象
			in = new BufferedReader(new InputStreamReader(client.getInputStream()));

			String content = "";
			do {
				content = in.readLine();
				System.out.println("收到消息：" + content);
			} while (!content.equals("88"));

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				// 关闭资源
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
				if (client != null) {
					client.close();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

	}

	/**
	 * 发送消息
	 * 
	 * @param message 要发送的消息
	 */
	public void sendMessage(String message) {
		try {
			out.write(message + "\r\n");

			out.flush();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	/**
	 * 关闭资源：socket、reader、writer
	 */
	public void close() {
		try {
			// 关闭资源
			if (out != null) {
				out.close();
			}

			if (in != null) {
				in.close();
			}

			if (client != null) {
				client.close();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

}
